package org.jeecg.modules.xl.order.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.erpx.api.CommonConstants;
import com.erpx.api.WdtClient;
import com.erpx.api.param.PlatformOrderCreateParam;
import com.erpx.api.param.PlatformOrderItemCreateParam;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.jeecg.boot.starter.lock.client.RedissonLockClient;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.base.service.BaseCommonService;
import org.jeecg.modules.xl.common.XlLogUtil;
import org.jeecg.modules.xl.h5api.vo.MyStoreDataVO;
import org.jeecg.modules.xl.h5api.vo.MyStoreVO;
import org.jeecg.modules.xl.kuaidi100.entity.XlKuaidi100Logitrace;
import org.jeecg.modules.xl.kuaidi100.service.IXlKuaidi100LogicomService;
import org.jeecg.modules.xl.kuaidi100.service.IXlKuaidi100LogitraceService;
import org.jeecg.modules.xl.kuaimai.entity.XlKuaimaiStock;
import org.jeecg.modules.xl.kuaimai.mapper.XlKuaimaiStockMapper;
import org.jeecg.modules.xl.kuaimai.service.KuaiMaiAPIService;
import org.jeecg.modules.xl.kuaimai.vo.KCOrderCreateDetail;
import org.jeecg.modules.xl.kuaimai.vo.KCOrderCreateParam;
import org.jeecg.modules.xl.logicmana.entity.XlCustomerLogisticPackage;
import org.jeecg.modules.xl.logicmana.service.IXlCustomerLogisticPackageService;
import org.jeecg.modules.xl.order.dto.XlCustomerOrdeDTO;
import org.jeecg.modules.xl.order.dto.XlCustomerShipmentDTO;
import org.jeecg.modules.xl.order.entity.XlCustomerOrde;
import org.jeecg.modules.xl.order.entity.XlCustomerOrderDetail;
import org.jeecg.modules.xl.order.entity.XlCustomerShipment;
import org.jeecg.modules.xl.order.entity.XlCustomerShipmentDetail;
import org.jeecg.modules.xl.order.enums.YesNoEnum;
import org.jeecg.modules.xl.order.mapper.XlCustomerOrdeMapper;
import org.jeecg.modules.xl.order.mapper.XlCustomerOrderDetailMapper;
import org.jeecg.modules.xl.order.mapper.XlCustomerShipmentMapper;
import org.jeecg.modules.xl.order.service.IXlCustomerOrdeService;
import org.jeecg.modules.xl.order.service.IXlCustomerOrderDetailService;
import org.jeecg.modules.xl.order.service.IXlCustomerShipmentDetailService;
import org.jeecg.modules.xl.order.utils.DictUtils;
import org.jeecg.modules.xl.order.utils.StrCommonUtil;
import org.jeecg.modules.xl.order.vo.OrderExport;
import org.jeecg.modules.xl.order.vo.OrderSheetDetail;
import org.jeecg.modules.xl.order.vo.XlCustomerOrdeCityVO;
import org.jeecg.modules.xl.order.vo.XlCustomerOrdeVO;
import org.jeecg.modules.xl.product.entity.XlProductInfo;
import org.jeecg.modules.xl.product.mapper.XlProductCustomerPriceMapper;
import org.jeecg.modules.xl.product.service.IXlProductInfoService;
import org.jeecg.modules.xl.shopcart.entity.XlShopcart;
import org.jeecg.modules.xl.store.entity.XlCustomerStoreInfo;
import org.jeecg.modules.xl.store.mapper.XlCustomerStoreInfoMapper;
import org.jeecg.modules.xl.store.service.IXlCustomerStoreInfoService;
import org.jeecg.modules.xl.wdt.entity.WdtGoodsSpecList;
import org.jeecg.modules.xl.wdt.mapper.WdtGoodsSpecListMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: xl_customer_order
 * @Author: jeecg-boot
 * @Date:   2024-10-20
 * @Version: V1.0
 */
@Service
@Slf4j
public class XlCustomerOrdeServiceImpl extends ServiceImpl<XlCustomerOrdeMapper, XlCustomerOrde> implements IXlCustomerOrdeService {

	@Autowired
	private XlCustomerOrdeMapper xlCustomerOrdeMapper;
	@Autowired
	private XlCustomerOrderDetailMapper xlCustomerOrderDetailMapper;
	@Resource
	private XlKuaimaiStockMapper xlKuaimaiStockMapper;

	@Autowired
	private XlLogUtil xlLogUtil ;

	@Autowired
	private IXlCustomerOrderDetailService xlCustomerOrderDetailService;
	@Autowired
	private DictUtils dictUtils;
	@Autowired
	private IXlProductInfoService xlProductInfoService;
	@Autowired
	private XlCustomerShipmentMapper xlCustomerShipmentMapper;
	@Autowired
	private IXlCustomerShipmentDetailService shipmentDetailService;
	@Autowired
	private XlCustomerStoreInfoMapper xlCustomerStoreInfoMapper;
	@Autowired
	private XlProductCustomerPriceMapper xlProductCustomerPriceMapper;
    @Autowired
    private IXlKuaidi100LogicomService iXlKuaidi100LogicomService;

    @Override
	public Page<XlCustomerOrdeVO> queryList(Page<XlCustomerOrde> page, Wrapper<XlCustomerOrde> wrapper) {
		return baseMapper.queryList(page,wrapper);
	}

	@Override
	public List<XlCustomerOrdeCityVO> queryCityList(String city, String orderCode) {
		return baseMapper.queryCityList(city,orderCode);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveMain(XlCustomerOrde xlCustomerOrde, List<XlCustomerOrderDetail> xlCustomerOrderDetailList) {
		/**商品总数量*/
		Double totalNum = Double.valueOf(0);
		/**商品种数*/
		Integer detailNum = 0;
		/**订单总金额*/
		Double totalAmount = 0.00;

		String pre = "HTM"+new SimpleDateFormat("yyMMdd").format(new Date());	//编码前缀

		//流水号
//		int maxNumber = StrCommonUtil.getStringNumber(baseMapper.queryMaxCodeNumber(pre));
//		xlCustomerOrde.setOrderCode(pre + String.format("%03d", maxNumber+1));
		String suffix = RandomUtil.randomNumbers(4);
		xlCustomerOrde.setOrderCode(pre+suffix);
		xlCustomerOrde.setPaymentState("-1");
		xlCustomerOrde.setOrderStatus("待提交");
		if(ObjectUtil.isEmpty(xlCustomerOrde.getProvince())){
			throw new JeecgBootException("订单门店缺少省份信息，请联系管理员核实！");
		}
		xlCustomerOrdeMapper.insert(xlCustomerOrde);

		if(xlCustomerOrderDetailList!=null && xlCustomerOrderDetailList.size()>0) {
			detailNum = xlCustomerOrderDetailList.size();
			for(XlCustomerOrderDetail entity:xlCustomerOrderDetailList) {
				//外键设置
				entity.setId(null);
				entity.setOrderId(xlCustomerOrde.getId());
				entity.setOrderCode(xlCustomerOrde.getOrderCode());
				entity.setCustomerTypeCode(xlCustomerOrde.getCustomerTypeCode());
				xlCustomerOrderDetailMapper.insert(entity);

				totalNum = totalNum + entity.getOrderQuantity().doubleValue();
				totalAmount = totalAmount + entity.getOrderAmount().doubleValue();
			}
		}

		//重新修改
		xlCustomerOrde.setTotalAmount(totalAmount);
		xlCustomerOrde.setTotalNum(totalNum);
		xlCustomerOrde.setDetailNum(detailNum);
		xlCustomerOrdeMapper.updateById(xlCustomerOrde);

		xlLogUtil.insertLog(xlCustomerOrde.getOrderCode(),"创建","订单创建",new Date(),"","待提交");

	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveOrderSheetMain(XlCustomerOrde xlCustomerOrde, List<OrderSheetDetail> orderSheetDetailList, String price_level) {
		/**商品总数量*/
		Double totalNum = Double.valueOf(0);
		/**商品种数*/
		Integer detailNum = 0;
		/**订单总金额*/
		Double totalAmount = 0.00;

		String pre = "HTM"+new SimpleDateFormat("yyMMdd").format(new Date());	//编码前缀

		//流水号
//		int maxNumber = StrCommonUtil.getStringNumber(baseMapper.queryMaxCodeNumber(pre));
//		xlCustomerOrde.setOrderCode(pre + String.format("%03d", maxNumber+1));
		String suffix = RandomUtil.randomNumbers(4);
		xlCustomerOrde.setOrderCode(pre+suffix);
		xlCustomerOrde.setPaymentState("-1");
		xlCustomerOrde.setOrderStatus("待提交");
		xlCustomerOrdeMapper.insert(xlCustomerOrde);//先要保存一下 才有主表的id
		//先处理明细
		//没有工单的id 故拿下来
		if(orderSheetDetailList!=null && orderSheetDetailList.size()>0) {
			//detailNum = orderSheetDetailList.size();
			for(OrderSheetDetail entity:orderSheetDetailList) {

				//外键设置
				XlCustomerOrderDetail po = new XlCustomerOrderDetail();
				BeanUtils.copyProperties(entity, po);
				po.setOrderId(xlCustomerOrde.getId());
				po.setOrderCode(xlCustomerOrde.getOrderCode());
				//2025-01-18 22:53:14 增加customer_type_code  区分渠道商品编码
				po.setCustomerTypeCode(xlCustomerOrde.getCustomerTypeCode());
				//查询产品
				/**
				 * 2025-01-18 06:13:50 更新，查询产品的方式 (门店渠道类型 & upc_code 或 other_code)
				 * 兼容导入的条码以,分割
				 * */
				QueryWrapper<XlProductInfo> productInfoQueryWrapper= new QueryWrapper();
				productInfoQueryWrapper.eq("type",xlCustomerOrde.getCustomerTypeCode());
				productInfoQueryWrapper.and(queryWrapper -> queryWrapper.in("upc_code",
								Arrays.asList(entity.getUpcCode().split(","))).or()
						.in("other_code",
								Arrays.asList(entity.getUpcCode().split(",")))) ;

//				XlProductInfo productInfo = xlProductInfoMapper.selectOne(productInfoQueryWrapper);
				Page<XlProductInfo> page = new Page<XlProductInfo>(1, 10);
				Page<XlProductInfo> productInfoListPage = xlProductCustomerPriceMapper.queryListByPage(page,productInfoQueryWrapper);
				XlProductInfo productInfo = null;
				if(ObjectUtil.isNotEmpty(productInfoListPage)&&ObjectUtil.isNotEmpty(productInfoListPage.getRecords())){
					if(productInfoListPage.getRecords().size() > 2){
						throw new JeecgBootException("渠道商品【"+entity.getUpcCode()+"】基础数据异常，有多个价格，请联系管理员核实！");
					}
					productInfo = productInfoListPage.getRecords().get(0);
				}
				if(ObjectUtil.isEmpty(productInfo)){
					//throw new JeecgBootException("商品【"+entity.getUpcCode()+"]主数据异常，请联系管理员！");
					//如果不存在产品 直接跳过
					continue;
				}
				detailNum++;
				po.setProductId(productInfo.getId());
				po.setUpcCode(productInfo.getUpcCode());
				if (ObjectUtil.isEmpty(entity.getNum())){
					throw new JeecgBootException("商品数量不能为空或为零！");
				}
				po.setOrderQuantity(BigDecimal.valueOf(entity.getNum()));
				if (ObjectUtil.isEmpty(productInfo.getSupplyPrice())){
					throw new JeecgBootException("渠道商品【"+entity.getUpcCode()+"】价格未维护，请联系管理员！");
				}
				po.setProductPrice(BigDecimal.valueOf(productInfo.getSupplyPrice()));
				po.setOrderAmount(po.getOrderQuantity().multiply(po.getProductPrice()));
				totalNum = totalNum + po.getOrderQuantity().doubleValue();
				totalAmount = totalAmount + po.getOrderAmount().doubleValue();
				xlCustomerOrderDetailMapper.insert(po);
			}
		}
		if (detailNum == 0){
			throw new JeecgBootException("订单明细不能为空！！");
		}
		//更新主表
		xlCustomerOrde.setTotalAmount(totalAmount);
		xlCustomerOrde.setTotalNum(totalNum);
		xlCustomerOrde.setDetailNum(detailNum);
		xlCustomerOrdeMapper.updateById(xlCustomerOrde);
		xlLogUtil.insertLog(xlCustomerOrde.getOrderCode(),"创建","订单导入",new Date(),"","待提交");


	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	@CacheEvict( value = "orderDetail" , key = "#xlCustomerOrde.orderCode" )
	public void updateMain(XlCustomerOrde xlCustomerOrde,List<XlCustomerOrderDetail> xlCustomerOrderDetailList) {

		//1.先删除子表数据
		xlCustomerOrderDetailMapper.deleteByMainId(xlCustomerOrde.getId());

		/**商品总数量*/
		Double totalNum = Double.valueOf(0);
		/**商品种数*/
		Integer detailNum = 0;
		/**订单总金额*/
		Double totalAmount = 0.00;

		//2.子表数据重新插入
		if(xlCustomerOrderDetailList!=null && xlCustomerOrderDetailList.size()>0) {

			detailNum  = xlCustomerOrderDetailList.size();
			for(XlCustomerOrderDetail tmp:xlCustomerOrderDetailList) {
				tmp.setId(null);//避免复制id
				XlCustomerOrderDetail entity = new XlCustomerOrderDetail();
				BeanUtils.copyProperties(tmp, entity);
				//外键设置
				entity.setOrderId(xlCustomerOrde.getId());
				entity.setOrderCode(xlCustomerOrde.getOrderCode());
				entity.setCustomerTypeCode(xlCustomerOrde.getCustomerTypeCode());
				//设置productID
				XlProductInfo tempss  = xlProductInfoService.getProductInfoCacheable(tmp.getUpcCode());
				entity.setProductId(tempss.getId());
				totalNum = totalNum + entity.getOrderQuantity().doubleValue();
				totalAmount = totalAmount + entity.getOrderAmount().doubleValue();
				xlCustomerOrderDetailMapper.insert(entity);
			}
		}
		xlCustomerOrde.setTotalAmount(totalAmount);
		xlCustomerOrde.setTotalNum(totalNum);
		xlCustomerOrde.setDetailNum(detailNum);
		xlCustomerOrdeMapper.updateById(xlCustomerOrde);
		xlLogUtil.insertLog(xlCustomerOrde.getOrderCode(),"编辑","订单编辑",new Date(),xlCustomerOrde.getOrderStatus(),xlCustomerOrde.getOrderStatus());

	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delMain(String id) {
//		if (this.count(Wrappers.lambdaQuery(XlCustomerOrde.class)
//						.eq(XlCustomerOrde::getId, id)
//						.not(XlCustomerOrde::getAuditState, dictUtils.getDictValue("audit_state", "审核通过"))
//		) > 0){
//			throw new JeecgBootException("订单已审核,不能删除！");
//		}

		xlCustomerOrderDetailMapper.deleteByMainId(id);
		xlCustomerOrdeMapper.deleteById(id);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delBatchMain(Collection<? extends Serializable> idList) {
		if (this.count(Wrappers.lambdaQuery(XlCustomerOrde.class)
				.in(XlCustomerOrde::getId, idList)
				.eq(XlCustomerOrde::getAuditState, dictUtils.getDictValue("audit_state", "审核通过"))
		) > 0){
			throw new JeecgBootException("选择的订单中有已审核的,不能删除！");
		}

		for(Serializable id:idList) {
			xlCustomerOrderDetailMapper.deleteByMainId(id.toString());
			xlCustomerOrdeMapper.deleteById(id);
		}
	}

    @Override
    public void audit(XlCustomerOrdeDTO dto) {
		//当前操作人
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		List<String> idList = Arrays.asList(dto.getId().split(","));//所有待审核的订单id
		List<XlCustomerOrde> list = this.listByIds(idList);//所有待审核的订单
		for(XlCustomerOrde xlCustomerOrdeTemp: list){
			String auditState = dto.getAuditState();//审核状态
			if("1".equals(auditState)){
				this.update(Wrappers.lambdaUpdate(XlCustomerOrde.class)
						.set(XlCustomerOrde::getAuditState, dto.getAuditState())
						.set(XlCustomerOrde::getAuditNote, dto.getAuditNote())
						.set(XlCustomerOrde::getAuditTime, new Date())
						.set(XlCustomerOrde::getAuditBy, user.getUsername())
						.set(XlCustomerOrde::getShipmentState, "0")
						.set(XlCustomerOrde::getOrderStatus, "待发货")
						.eq(XlCustomerOrde::getId, xlCustomerOrdeTemp.getId())
				);
				xlLogUtil.insertLog(xlCustomerOrdeTemp.getOrderCode(),"审核","订单审核",new Date(),xlCustomerOrdeTemp.getOrderStatus(),"待发货");

			}else{
				this.update(Wrappers.lambdaUpdate(XlCustomerOrde.class)
						.set(XlCustomerOrde::getAuditState, dto.getAuditState())
						.set(XlCustomerOrde::getAuditNote, dto.getAuditNote())
						.set(XlCustomerOrde::getAuditTime, new Date())
						.set(XlCustomerOrde::getAuditBy, user.getUsername())
						.set(XlCustomerOrde::getShipmentState, "0")
						.set(XlCustomerOrde::getOrderStatus, "拒绝")
						.eq(XlCustomerOrde::getId, xlCustomerOrdeTemp.getId())
				);

				xlLogUtil.insertLog(xlCustomerOrdeTemp.getOrderCode(),"审核","订单审核",new Date(),xlCustomerOrdeTemp.getOrderStatus(),"拒绝");
			}
		}

		//new XlLogUtil().insertLog(dto.getOrderCode(),"审核","订创审核",new Date(),"待审核","待发货");

	}

	@Override
	public void payment(XlCustomerOrdeDTO dto) {
		//标记欠款
		//当前操作人
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		this.update(Wrappers.lambdaUpdate(XlCustomerOrde.class)
				.set(XlCustomerOrde::getAuditState, dto.getAuditState())
				.set(XlCustomerOrde::getAuditNote, dto.getAuditNote())
				.set(XlCustomerOrde::getAuditTime, new Date())
				.set(XlCustomerOrde::getAuditBy, user.getUsername())
				.set(XlCustomerOrde::getShipmentState, "0")
				.set(XlCustomerOrde::getIsDebt,"欠款送审")
				.set(XlCustomerOrde::getOrderStatus, "待审核")
				.eq(XlCustomerOrde::getId, dto.getId())
		);
		XlCustomerOrde orde = this.getById(dto.getId());
		xlLogUtil.insertLog(orde.getOrderCode(),"欠款送审","欠款送审",new Date(),"待支付","待审核");
	}

	@Override
	@Transactional
	public void shipment(XlCustomerShipmentDTO dto) {
		//当前操作人
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		List<String> idList = Lists.newArrayList();

		XlCustomerOrde orde = this.getById(dto.getId());
		if (orde != null){
			idList.add(orde.getId());

			//判断是否未支付或已发货
//			if (orde.getPaymentState() == null || !dictUtils.getDictValue("payment_state","已支付").equals(orde.getPaymentState())) {
//				throw new JeecgBootException("未支付的订单,不能操作！");
//			}
			//商品明细id集合
			List<String> deatilIds = dto.getXlCustomerOrderDetailList().stream().map(m -> m.getId()).collect(Collectors.toList());
			List<XlCustomerShipmentDetail> detailList = shipmentDetailService.list(Wrappers.lambdaQuery(XlCustomerShipmentDetail.class)
					.select(XlCustomerShipmentDetail::getOrderDetailId)
					.in(XlCustomerShipmentDetail::getOrderDetailId, deatilIds)
			);
			if (detailList.size() > 0){
				List<String> collect = detailList.stream().map(m -> m.getOrderDetailId()).collect(Collectors.toList());
				throw new JeecgBootException("选中的商品【"+dto.getXlCustomerOrderDetailList().stream().filter(f-> collect.contains(f.getId())).map(m-> m.getProductName()).collect(Collectors.joining(","))
						+"】已发货,不能重复操作！");
			}

		}else{
			throw new JeecgBootException("该订单id找不到对应数据："+dto.getId());
		}

		//新建发货单
		XlCustomerShipment shipment = new XlCustomerShipment();
		BeanUtils.copyProperties(dto, shipment);

		shipment.setDeliveryWay(orde.getDeliveryWay());	//发货方式;
		shipment.setShipmentCode("FH" + RandomUtil.randomNumbers(13));	//编号生成;
		shipment.setState(dictUtils.getDictValue("customer_shipment_state","已发货")); //发货单状态

		xlCustomerShipmentMapper.insert(shipment);

		//发货单明细
		ArrayList<XlCustomerShipmentDetail> detailList = Lists.newArrayList();
		for (XlCustomerOrderDetail d : dto.getXlCustomerOrderDetailList()) {
			XlCustomerShipmentDetail detail = new XlCustomerShipmentDetail();
			detail.setOrderDetailId(d.getId());
			detail.setShipmentCode(shipment.getShipmentCode());
			detail.setOrderCode(shipment.getOrderCode());

			detailList.add(detail);
		}
		shipmentDetailService.saveBatch(detailList);

		///判断是否都已发货 是则修改订单未已发货
		List<XlCustomerOrderDetail> details = xlCustomerOrderDetailMapper.queryOrderDetailNotShipmentById(orde.getId());
		if (details.size() < 1) {
			//修改为已发货
			this.update(Wrappers.lambdaUpdate(XlCustomerOrde.class)
					.set(XlCustomerOrde::getShipmentState, dictUtils.getDictValue("customer_shipment_state","已发货"))
					.set(XlCustomerOrde::getShipmentTime, new Date())
					.set(XlCustomerOrde::getShipmentBy, user.getUsername())
					.eq(XlCustomerOrde::getId, orde.getId())
			);
		}

	}


	@Value("${pichost}")
	private String baseUrl;
    @Override
    public void submitPayment(XlCustomerOrdeDTO dto) {
		//当前操作人
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		XlCustomerOrde orde = this.getById(dto.getId());
		if(ObjectUtil.isEmpty(orde)){
			throw new JeecgBootException("无法找到订单！");
		}
		if(!"待支付".equals(orde.getOrderStatus())&&!"欠款送审".equals(orde.getIsDebt())){
			throw new JeecgBootException("该订单:"+orde.getOrderCode()+"已提交支付凭证也不是欠款审核,不能操作！");
		}

		if("欠款送审".equals(orde.getIsDebt() )) {
			String paymentImage = dto.getImage();
			if(paymentImage.contains(baseUrl)){
				//替换凭证的 baseurl
				dto.setImage(paymentImage.replace(baseUrl,""));
			}
			//欠款送审订单 上传 支付凭证
			this.update(Wrappers.lambdaUpdate(XlCustomerOrde.class)
					.set(XlCustomerOrde::getPaymentState, dictUtils.getDictValue("payment_state","已支付"))
					.set(XlCustomerOrde::getPaymentImage, dto.getImage())
					.set(XlCustomerOrde::getPaymentBy, user.getUsername())
					.set(XlCustomerOrde::getPaymentAmount, dto.getPaymentAmount())
					.set(XlCustomerOrde::getPaymentTime, new Date())
					.set(XlCustomerOrde::getIsDebt,null)
					.eq(XlCustomerOrde::getId, dto.getId())
			);
			xlLogUtil.insertLog(orde.getOrderCode(),"上传支付凭证","上传支付凭证，消除欠款",new Date(),orde.getOrderStatus(),orde.getOrderStatus());
		}else{
			//待支付订单 上传 支付凭证
			this.update(Wrappers.lambdaUpdate(XlCustomerOrde.class)
					.set(XlCustomerOrde::getPaymentState, dictUtils.getDictValue("payment_state","已支付"))
					.set(XlCustomerOrde::getPaymentImage, dto.getImage())
					.set(XlCustomerOrde::getPaymentBy, user.getUsername())
					.set(XlCustomerOrde::getPaymentAmount, dto.getPaymentAmount())
					.set(XlCustomerOrde::getPaymentTime, new Date())
					.set(XlCustomerOrde::getOrderStatus, "待审核")
					.eq(XlCustomerOrde::getId, dto.getId())
			);
			xlLogUtil.insertLog(orde.getOrderCode(),"上传支付凭证","上传支付凭证,完成支付",new Date(),"待支付","待审核");
		}

	}

	public Result<String> shouhuo(String orderids){
		Result<String> stringResult = new Result<>();
		List<String> idList = Lists.newArrayList();
		idList.addAll(Arrays.asList(orderids.split(",")));
		List<XlCustomerOrde> list = this.listByIds(idList);
		for(XlCustomerOrde  xlCustomerOrde : list){
			if( !"待收货".equals(xlCustomerOrde.getOrderStatus())){
				//订单不是未提交状态
				stringResult.setSuccess(false);
				stringResult.setMessage("订单【"+xlCustomerOrde.getOrderCode()+"]不是待收货状态,不能点击收货，请导入物流！");
				return stringResult;
			}else{
				LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
				//修改为 待审批，并且更新汇总字段
				this.update(Wrappers.lambdaUpdate(XlCustomerOrde.class)
						.set(XlCustomerOrde::getOrderStatus,"已收货")
						.set(XlCustomerOrde::getUpdateTime,new Date())
						.set(XlCustomerOrde::getUpdateBy, user.getUsername())
						.in(XlCustomerOrde::getId, xlCustomerOrde.getId())
				);
				xlLogUtil.insertLog(xlCustomerOrde.getOrderCode(),"收货","提交",new Date(),"待收货","已收货");
				return Result.ok("收货成功");
			}
		}
		return stringResult;
	}


	@Autowired
	private BaseCommonService baseCommonService  ;
	@Autowired
	private RedissonLockClient redissonLock;

	@Override
	@Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
	public Result<String> submit(XlCustomerOrdeDTO dto) {
		Result<String> stringResult = new Result<>();
		try{
			redissonLock.tryLock("redisson_stock", -1, 10000);
			//当前操作人
			//LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			List<String> idList = Lists.newArrayList();
			idList.addAll(Arrays.asList(dto.getId().split(",")));
			List<XlCustomerOrde> list = this.listByIds(idList);
			for(XlCustomerOrde  xlCustomerOrde : list){
				if( !"-1".equals(xlCustomerOrde.getAuditState()) ||!"待提交".equals(xlCustomerOrde.getOrderStatus())){
					//订单不是未提交状态
					stringResult.setSuccess(false);
					stringResult.setMessage("订单【"+xlCustomerOrde.getOrderCode()+"]已提交,不能重复提交！");
					return stringResult;
					//throw new JeecgBootException("订单【"+xlCustomerOrde.getOrderCode()+"]已提交,不能重复提交！");
				}
				//判断库存
				List<XlCustomerOrderDetail>  xlCustomerOrderDetailList = xlCustomerOrderDetailMapper.selectByMainId(xlCustomerOrde.getId());
				if(ObjectUtil.isEmpty(xlCustomerOrderDetailList)){
					//订单缺少明细
					//throw new JeecgBootException("订单【"+xlCustomerOrde.getOrderCode()+"]缺少明细，订单数据异常,无法提交！");
					stringResult.setSuccess(false);
					stringResult.setMessage("订单【"+xlCustomerOrde.getOrderCode()+"]缺少明细，订单数据异常,无法提交！");
				}
				//根据商品UPCCode查询库存
				List<String> productUPCStrs = xlCustomerOrderDetailList.stream().map(m -> m.getUpcCode()).collect(Collectors.toList());
				QueryWrapper<XlKuaimaiStock> ss = new QueryWrapper<>();
				ss.in(productUPCStrs.size()>0,"mainOuterId",productUPCStrs);
				//ss.eq("mainOuterId","6934660516714");
				List<XlKuaimaiStock> stockList = xlKuaimaiStockMapper.selectList(ss);
				// 将 List<XlKuaimaiStock> 转换为 Map<String, XlKuaimaiStock>
				Map<String, XlKuaimaiStock> stockMap = stockList.stream()
						.collect(Collectors.toMap(XlKuaimaiStock::getMainouterid, stock -> stock));
				StringBuffer notHaveStockProduct = new StringBuffer();
				boolean stockFull = true;
				List<XlKuaimaiStock> stockListUpdate = new ArrayList<>();
				double totalamout = xlCustomerOrde.getTotalAmount();
				double totalnum = xlCustomerOrde.getTotalNum();
				int detailnum = xlCustomerOrde.getDetailNum();

				List<String> idsDelete = new ArrayList<>();

				for(XlCustomerOrderDetail orderDetail : xlCustomerOrderDetailList){
					//-- 需要删除的商品 库存为0

					//一一判断库存
					XlKuaimaiStock stock =  stockMap.get(orderDetail.getUpcCode());
					long totalAvailableStockSum = 0;
					long sltLockStock = 0;
					long sltAvailableStock = 0;
					if(ObjectUtil.isNotEmpty(stock)){
						totalAvailableStockSum = stock.getTotalavailablestocksum();
						sltLockStock = stock.getSltLockStock();
						sltAvailableStock = stock.getSltAvailableStock();
					}
					if(sltAvailableStock <= 0 || sltAvailableStock < orderDetail.getOrderQuantity().longValue()){//可以库存为0 或作 可用库存小于订单数量
						stockFull= false;
						//订单缺少明细
						notHaveStockProduct.append(orderDetail.getUpcCode()+",");
						//log.info("订单{}-商品{}-校验库存-订单数{}-库存数{}，库存不足",xlCustomerOrde.getOrderCode(),orderDetail.getUpcCode(),orderDetail.getOrderQuantity(),stock.getSltAvailableStock());
						String logStr = "订单："+xlCustomerOrde.getOrderCode()+"-商品-"+orderDetail.getUpcCode()+"-校验库存-订单数： "+orderDetail.getOrderQuantity()+"-库存数："+ sltAvailableStock +"，库存不足";

						log.info(logStr);
						//如果库存不存在，就直接删除该商品明细,并且也需要更新订单里的汇总信息
						idsDelete.add(orderDetail.getId());
						totalamout = totalamout - orderDetail.getOrderAmount().doubleValue();
						totalnum = totalnum - orderDetail.getOrderQuantity().doubleValue();
						detailnum = detailnum -1;

						continue;
					}
					log.info("订单{}-商品{}-校验库存-订单数{}-库存数{}，库存充足",xlCustomerOrde.getOrderCode(),orderDetail.getUpcCode(),orderDetail.getOrderQuantity(),sltAvailableStock);
					String logStr = "订单:"+xlCustomerOrde.getOrderCode()+"-商品-"+orderDetail.getUpcCode()+"-校验库存-订单数:"+orderDetail.getOrderQuantity()+"-库存数:"+sltAvailableStock +"，库存不足";
					//baseCommonService.addLog(logStr, CommonConstant.OPERATE_TYPE_kucun_7, null);
					XlKuaimaiStock xlKuaimaiStocknew = new XlKuaimaiStock();
					BeanUtils.copyProperties(stock,xlKuaimaiStocknew);
					xlKuaimaiStocknew.setSltLockStock(stock.getSltLockStock() + orderDetail.getOrderQuantity().longValue());//占用库存
					xlKuaimaiStocknew.setSltAvailableStock(stock.getSltAvailableStock() -  orderDetail.getOrderQuantity().longValue());

					stockListUpdate.add(xlKuaimaiStocknew);
				}
				//如果订单所有商品都没有库存，就不允许提交了。
				if(detailnum == 0){
					stringResult.setSuccess(true);
					stringResult.setMessage("订单所有的商品都没有库存，无法提交！！");
					return stringResult;
				}
				//如果存在库存为0的商品，就直接删除
				if(idsDelete.size()>0){
					xlCustomerOrderDetailMapper.deleteBatchIds(idsDelete);
				}

				//更新库存
				for (XlKuaimaiStock stockupdate: stockListUpdate){
					xlKuaimaiStockMapper.updateById(stockupdate);
				}
				//修改为 待审批，并且更新汇总字段
				this.update(Wrappers.lambdaUpdate(XlCustomerOrde.class)
						.set(XlCustomerOrde::getAuditState, dictUtils.getDictValue("audit_state","待审核"))
						.set(XlCustomerOrde::getOrderStatus,"待支付")
						.set(XlCustomerOrde::getTotalAmount,totalamout)
						.set(XlCustomerOrde::getTotalNum, totalnum)
						.set(XlCustomerOrde::getDetailNum, detailnum)
						.in(XlCustomerOrde::getId, xlCustomerOrde.getId())
				);
				stringResult.setSuccess(true);
				if(!stockFull){
					stringResult.setMessage("订单【"+xlCustomerOrde.getOrderCode()+"】提交成功，其中商品："+notHaveStockProduct+" 无货");
				}else{
					stringResult.setMessage("所有商品库存充足，订单【"+xlCustomerOrde.getOrderCode()+"】提交成功");
				}
				xlLogUtil.insertLog(xlCustomerOrde.getOrderCode(),"订单提交","提交",new Date(),"待提交","待支付");

			}
		} catch (Exception e){
			e.printStackTrace();
			String logStr = "订单："+dto.getId()+" 校验库存失败，有异常！";
			baseCommonService.addLog(logStr, CommonConstant.OPERATE_TYPE_kucun_7, null);
			//throw new JeecgBootException("订单【锁库存】提交失败，请重试！");
			stringResult.setSuccess(false);
			stringResult.setMessage("订单【锁库存】提交失败，请重试！");
		}finally {
			redissonLock.unlock("redisson_stock");
		}
		return  stringResult;
	}

    @Override
    public void cityShipment(String city) {
		//当前操作人
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		//城配订单
		List<XlCustomerOrde> cityList = this.list(Wrappers.lambdaQuery(XlCustomerOrde.class)
				.eq(XlCustomerOrde::getDeliveryWay, dictUtils.getDictValue("delivery_way", "城配"))
				.eq(XlCustomerOrde::getIsCity, YesNoEnum.NO.getKey())
				.eq(XlCustomerOrde::getCity, city)
		);

		if (cityList.isEmpty()) {
			throw new JeecgBootException("当前城市【"+city+"】没有可城配发货的订单");
		}

		//城配订单id集合
		List<String> idS = cityList.stream().map(m -> m.getId()).collect(Collectors.toList());
		//订单编号集合
		String codeS = cityList.stream().map(m -> m.getOrderCode()).collect(Collectors.joining(","));

		//新建发货单
		XlCustomerShipment shipment = new XlCustomerShipment();
		shipment.setOrderCode(codeS);	//订单编号集合;
		shipment.setDeliveryWay(dictUtils.getDictValue("customer_shipment_state","已发货"));	//发货方式;
		shipment.setShipmentCode("FH" + RandomUtil.randomNumbers(13));	//编号生成;
		shipment.setState(dictUtils.getDictValue("customer_shipment_state","已发货")); //发货单状态

		xlCustomerShipmentMapper.insert(shipment);

		//订单下的商品信息
		List<XlCustomerOrderDetail> details = xlCustomerOrderDetailMapper.selectList(Wrappers.lambdaQuery(XlCustomerOrderDetail.class)
				.in(XlCustomerOrderDetail::getOrderId, idS)
		);
		//发货单明细
		ArrayList<XlCustomerShipmentDetail> detailList = Lists.newArrayList();
		for (XlCustomerOrderDetail d : details) {
			XlCustomerShipmentDetail detail = new XlCustomerShipmentDetail();
			detail.setOrderDetailId(d.getId());
			detail.setShipmentCode(shipment.getShipmentCode());
			detail.setOrderCode(shipment.getOrderCode());

			detailList.add(detail);
		}
		shipmentDetailService.saveBatch(detailList);

		//修改为已发货
		this.update(Wrappers.lambdaUpdate(XlCustomerOrde.class)
				.set(XlCustomerOrde::getShipmentState, dictUtils.getDictValue("customer_shipment_state","已发货"))
				.set(XlCustomerOrde::getShipmentTime, new Date())
				.set(XlCustomerOrde::getShipmentBy, user.getUsername())
				.set(XlCustomerOrde::getIsCity, YesNoEnum.YES.getKey())
				.in(XlCustomerOrde::getId, idS)
		);
    }

	@Override
	public List<OrderExport> exportOrderDetailS(QueryWrapper<OrderExport> queryWrapper) {
		return baseMapper.exportOrderDetailS(queryWrapper);
	}
	@Override
	public List<XlCustomerOrde> exportOnlyOrder(QueryWrapper<OrderExport> queryWrapper) {
		return baseMapper.exportOnlyOrder(queryWrapper);
	}
	@Override
	public void copyToCreate(XlCustomerOrdeDTO dto) {

		XlCustomerOrde orderTemp= this.getById(dto.getId());
		//查询明细
		List<XlCustomerOrderDetail> xlCustomerOrderDetailList = xlCustomerOrderDetailMapper.selectByMainId(orderTemp.getId());

		orderTemp.setCreateBy(null);
		orderTemp.setCreateTime(null);
		orderTemp.setAuditBy(null);
		orderTemp.setAuditState("-1");
		orderTemp.setAuditBy(null);
		orderTemp.setAuditTime(null);
		orderTemp.setShipmentState(null);
		orderTemp.setUpdateBy(null);
		orderTemp.setUpdateTime(null);
		orderTemp.setId(null);
		orderTemp.setDeliveryType(null);
		orderTemp.setPaymentBy(null);
		orderTemp.setPaymentState(null);
		orderTemp.setPaymentImage(null);
		orderTemp.setPaymentTime(null);
		XlCustomerOrde po = new XlCustomerOrde();

		BeanUtils.copyProperties(orderTemp, po);
		String pre = "HTM"+new SimpleDateFormat("yyMMdd").format(new Date());	//编码前缀

		//流水号
		int maxNumber = StrCommonUtil.getStringNumber(baseMapper.queryMaxCodeNumber(pre));

		po.setOrderCode(pre + String.format("%03d", maxNumber+1));
		po.setKmSid(null);
		//插入主表
		baseMapper.insert(po);


		if(xlCustomerOrderDetailList!=null && xlCustomerOrderDetailList.size()>0) {
			for(XlCustomerOrderDetail entity:xlCustomerOrderDetailList) {
				entity.setId(null);
				entity.setCreateBy(null);
				entity.setCreateTime(null);
				XlCustomerOrderDetail detailPo = new XlCustomerOrderDetail();

				BeanUtils.copyProperties(entity,detailPo);
				detailPo.setOrderCode(po.getOrderCode());
				detailPo.setOrderId(po.getId());
				detailPo.setShipmentState(null);
				detailPo.setKmSid(null);
				//插入子表
				xlCustomerOrderDetailMapper.insert(detailPo);
			}
		}

	}

	@Override
	public Result<String> createKMOrder(String orderids) {
		try {
			Result<String> result = new Result<>();
			List<String> orderList = Arrays.asList(orderids.split(","));
			StringBuilder msg = new StringBuilder();
			for(String orderid : orderList){
				//查询订单
				XlCustomerOrde orderInfo = xlCustomerOrdeMapper.selectOne(Wrappers.lambdaQuery(XlCustomerOrde.class)
						.eq(XlCustomerOrde::getId, orderid )
				);
				if(ObjectUtil.isEmpty(orderInfo.getProvince())){
					//bugfix 20250728： 修复订单的省份数据消失的异常问题
					QueryWrapper<XlCustomerStoreInfo> storeTargetWrapper = new QueryWrapper<>();
					storeTargetWrapper.eq("store_code",orderInfo.getStoreCode());
					XlCustomerStoreInfo storeTarget = xlCustomerStoreInfoMapper.selectOne(storeTargetWrapper);
					XlCustomerOrde xlCustomerOrdeTarget  = new XlCustomerOrde();
					xlCustomerOrdeTarget.setId(orderid);
					xlCustomerOrdeTarget.setProvince(storeTarget.getProvince());
					xlCustomerOrdeMapper.updateById(xlCustomerOrdeTarget);
				}
				if("待提交".equals(orderInfo.getOrderStatus())||"待支付".equals(orderInfo.getOrderStatus())||"待审核".equals(orderInfo.getOrderStatus())){
					return Result.error("所选订单为 待提交、待支付、待审核 状态，无法回传快麦，请核操作！");
				}
				if(ObjectUtil.isEmpty(orderInfo)){
					msg.append("订单： 回传快麦失败，原因是：订单数异常"+"\n");
					continue;
				}
				//查询订单明细
				QueryWrapper<XlCustomerOrderDetail> detailQueryWrapper = new QueryWrapper<>();
				detailQueryWrapper.eq("order_id",orderid);
				List<XlCustomerOrderDetail> orderDetails = xlCustomerOrderDetailMapper.selectList(detailQueryWrapper);
				if(ObjectUtil.isEmpty(orderDetails)){
					msg.append("订单： 回传快麦失败，原因是：订单数异常"+"\n");
					continue;
				}
				//构造接口参数
				KCOrderCreateParam param = new KCOrderCreateParam();
				List s = new ArrayList<KCOrderCreateDetail>();
				for(XlCustomerOrderDetail orderDetail : orderDetails){
					KCOrderCreateDetail orderCreateDetail = new KCOrderCreateDetail();
					orderCreateDetail.setOuterSkuId(orderDetail.getUpcCode());
					orderCreateDetail.setNum(orderDetail.getOrderQuantity().intValue());
					orderCreateDetail.setPrice(String.valueOf(orderDetail.getProductPrice().doubleValue()));
					orderCreateDetail.setPayment(String.valueOf(orderDetail.getOrderAmount().doubleValue()));
					s.add(orderCreateDetail);
				}

				param.setTid(orderInfo.getOrderCode());////平台订单号(相同tid只能推送一次)
				param.setUserId("900234972");//店铺编号
				param.setWarehouseId("458153");//  仓库ID
				param.setOrders(JSONUtil.toJsonStr(s));// 订单商品明细集合
				param.setPayment(String.valueOf(orderInfo.getTotalAmount()));;// 实付金额（例如1.00）（单位：元）
				param.setReceiverName(orderInfo.getReceiptName());// 收件人姓名
				param.setReceiverState(orderInfo.getProvince());//收件省份
				param.setReceiverCity(orderInfo.getCity());;// 收件市
				param.setReceiverDistrict(orderInfo.getDistrict());;//收件区县
				param.setReceiverAddress(orderInfo.getReceiptAddress());//收件详细地址
				param.setReceiverMobile(orderInfo.getReceiptPhone());
				param.setForce("true");
				param.setPayTime(DateUtil.formatDateTime(orderInfo.getCreateTime()));
				String resultJsonStr = new KuaiMaiAPIService().createKMOrder(param);
				JSON resultJson = JSONUtil.parseObj(resultJsonStr);
				boolean success  =  Boolean.valueOf(resultJson.getByPath("success").toString());
				String traceId = resultJson.getByPath("traceId").toString();
				if(success){
					//接口调用成功
					String sid = resultJson.getByPath("sid").toString();
					//更新订单的km_sid
					orderInfo.setKmSid(sid);
					xlCustomerOrdeMapper.updateById(orderInfo);
					//更新明细的km_sid
					for(XlCustomerOrderDetail orderDetailTemp : orderDetails){
						orderDetailTemp.setKmSid(sid);
						xlCustomerOrderDetailMapper.updateById(orderDetailTemp);
					}
					msg.append("订单："+orderInfo.getOrderCode()+" 回传快麦成功，sid是："+sid+"\n");
					//return  Result.ok("回传快麦成功，单号是：" + sid);
					xlLogUtil.insertLog(orderInfo.getOrderCode(),"回传快麦","回传快麦成功,traceId是："+traceId,new Date(),orderInfo.getOrderStatus(),orderInfo.getOrderStatus());

				}else {
					msg.append("订单："+orderInfo.getOrderCode()+" 回传快麦失败，原因是："+resultJson.getByPath("msg").toString()+" 快麦traceId是："+traceId);
					xlLogUtil.insertLog(orderInfo.getOrderCode(),"回传快麦","回传快麦失败,traceId是："+traceId,new Date(),orderInfo.getOrderStatus(),orderInfo.getOrderStatus());
					//return Result.error("回传快麦失败，原因是："+resultJson.getByPath("msg").toString());
				}
			}
			return  Result.ok(msg.toString());

		}catch (Exception e){
			e.printStackTrace();
			return Result.error("回传快麦失败，原因未知");
		}
	}

	public Map<String,Map<String, Object>> selectOrdersAfterAmount(@Param("orders") String orders){
		return baseMapper.selectOrdersAfterAmount(orders);
	}

	@Override
	public List<MyStoreDataVO> getMyStoreData(String stores) {
		return baseMapper.getMyStoreData(stores);
	}


	@Autowired
	private IXlCustomerStoreInfoService storeInfoService;
	//根据购物车，提交订单
	@Override
	public XlCustomerOrde  submitOrder(String storeCode, List<XlShopcart> shopcarts,String orderNote) {

		QueryWrapper<XlCustomerStoreInfo> storeInfoQueryWrapper = new QueryWrapper<>();
		storeInfoQueryWrapper.eq("store_code",storeCode);
		//查询门店信息
		XlCustomerStoreInfo storeInfoTargget  = storeInfoService.getStoreInfoCacheable(storeCode);
		if(ObjectUtil.isEmpty(storeInfoTargget)){
			return null;
		}


		String pre = "HTMWX"+new SimpleDateFormat("yyMMdd").format(new Date());	//编码前缀
		//流水号
		int maxNumber = StrCommonUtil.getStringNumber(baseMapper.queryMaxCodeNumber(pre));

		XlCustomerOrde xlCustomerOrde = new XlCustomerOrde();
		xlCustomerOrde.setOrderCode(pre + String.format("%03d", maxNumber+1));
		xlCustomerOrde.setCustomerType(storeInfoTargget.getCustomerType());
		xlCustomerOrde.setCustomerTypeCode(storeInfoTargget.getCustomerTypeCode());
		xlCustomerOrde.setStoreCode(storeCode);
		xlCustomerOrde.setStoreName(storeInfoTargget.getStoreName());
		xlCustomerOrde.setOrderNotes(orderNote);
		xlCustomerOrde.setIsCity("0");
		xlCustomerOrde.setReceiptName(storeInfoTargget.getStoreManager());
		xlCustomerOrde.setReceiptPhone(storeInfoTargget.getStoreManagerPhone());
		xlCustomerOrde.setProvince(storeInfoTargget.getProvince());
		xlCustomerOrde.setCity(storeInfoTargget.getCity());
		xlCustomerOrde.setDistrict(storeInfoTargget.getDistrict());
		xlCustomerOrde.setReceiptZone(storeInfoTargget.getProvince()+storeInfoTargget.getCity()+storeInfoTargget.getDistrict());
		xlCustomerOrde.setReceiptAddress(storeInfoTargget.getStoreAddress());
		xlCustomerOrde.setOrderStatus("待支付");
		xlCustomerOrde.setAuditState("-1");//待审核
		xlCustomerOrde.setAuditTime(new Date());
		xlCustomerOrde.setPaymentState("-1");
		xlCustomerOrde.setShipmentState("0");
		xlCustomerOrde.setDeliveryWay("2");
		xlCustomerOrde.setDeliveryType("1");
		xlCustomerOrde.setOrderNotes(orderNote);


		xlCustomerOrdeMapper.insert(xlCustomerOrde);
		xlLogUtil.insertLog(xlCustomerOrde.getOrderCode(),"小程序提交订单","提交",new Date(),"","待支付");

		/**商品总数量*/
		Double totalNum = Double.valueOf(0);
		/**商品种数*/
		Integer detailNum = 0;
		/**订单总金额*/
		Double totalAmount = 0.00;
		if(shopcarts!=null && shopcarts.size()>0) {
			detailNum = shopcarts.size();
			for(XlShopcart shopcart:shopcarts) {
				XlCustomerOrderDetail entity = new XlCustomerOrderDetail();
				//外键设置
				entity.setId(null);
				entity.setOrderId(xlCustomerOrde.getId());
				entity.setOrderCode(xlCustomerOrde.getOrderCode());
				entity.setProductId(null);
				entity.setCustomerTypeCode(xlCustomerOrde.getCustomerTypeCode());
				entity.setUpcCode(shopcart.getUpcCode());
				entity.setProductPrice(shopcart.getPrice());
				entity.setOrderQuantity(BigDecimal.valueOf(shopcart.getQuantity()));
				entity.setOrderAmount(entity.getProductPrice().multiply(entity.getOrderQuantity()));
				entity.setShipmentState("0");
				xlCustomerOrderDetailMapper.insert(entity);
				totalNum = totalNum + entity.getOrderQuantity().doubleValue();
				totalAmount = totalAmount + entity.getOrderAmount().doubleValue();
			}
		}

		//更新订单汇总数据
		xlCustomerOrde.setTotalAmount(totalAmount);
		xlCustomerOrde.setTotalNum(totalNum);
		xlCustomerOrde.setDetailNum(detailNum);
		xlCustomerOrdeMapper.updateById(xlCustomerOrde);

		return xlCustomerOrde;
	}

	@Override
	public MyStoreVO getStoreUnpayAmount(String storeCode) {
		  List<MyStoreVO> list = xlCustomerOrdeMapper.getStoreUnpayAmount(storeCode);
		  MyStoreVO myStoreVO = new MyStoreVO();
		  myStoreVO.setStoreCode(storeCode);
		  if(ObjectUtil.isEmpty(list)){
			  myStoreVO.setUnpayAmount(BigDecimal.valueOf(0l));
			  return  myStoreVO;
		  }else{
			  BigDecimal total = list.stream ( ).map ( MyStoreVO::getUnpayAmount ).filter ( Objects :: nonNull ).reduce (BigDecimal.ZERO , BigDecimal::add ) ;
			  myStoreVO.setUnpayAmount(total);
		  }
		  return myStoreVO;
	}

	public List<Map> getCornerNum(String storeCode){
		return  baseMapper.getCornerNum(storeCode);
	}

	@Override
	public XlCustomerOrde getOneByCode(String orderCode) {
		QueryWrapper<XlCustomerOrde> xlCustomerOrdeQueryWrapper= new QueryWrapper();
		xlCustomerOrdeQueryWrapper.eq("order_code",orderCode);
		return baseMapper.selectOne(xlCustomerOrdeQueryWrapper);
	}

	@Override
	public List<XlCustomerOrderDetail> getDetailByCode(String orderCode) {
		QueryWrapper<XlCustomerOrderDetail> xlCustomerOrderDetailQueryWrapper= new QueryWrapper();
		xlCustomerOrderDetailQueryWrapper.eq("order_code",orderCode);
		return xlCustomerOrderDetailMapper.selectList(xlCustomerOrderDetailQueryWrapper);
	}
	@Resource
	private WdtGoodsSpecListMapper wdtGoodsSpecListMapper;
	@Override
	public Result<String> createWDTOrder(String orderids) {
		try {
			Result<String> result = new Result<>();
			String[] orderList = orderids.split(",");
			StringBuilder msg = new StringBuilder();
			//List<PlatformOrderCreateParam> trade_list = new ArrayList<>();
			//List<XlCustomerOrde> targetOrderList = new ArrayList<>();
			for(String orderid : orderList){
				List<PlatformOrderCreateParam> trade_list = new ArrayList<>();
				//查询订单
				XlCustomerOrde orderInfo = xlCustomerOrdeMapper.selectOne(Wrappers.lambdaQuery(XlCustomerOrde.class)
						.eq(XlCustomerOrde::getId, orderid )
				);
				if("待提交".equals(orderInfo.getOrderStatus())||"待支付".equals(orderInfo.getOrderStatus())||"待审核".equals(orderInfo.getOrderStatus())){
					return Result.error("所选订单为 待提交、待支付、待审核 状态，无法回传快麦，请核操作！");
				}
				if(ObjectUtil.isEmpty(orderInfo)){
					msg.append(StrUtil.format("订单：{} 旺店通失败，原因是：订单数据异常",orderid));
					continue;
				}
				//查询订单明细
				QueryWrapper<XlCustomerOrderDetail> detailQueryWrapper = new QueryWrapper<>();
				detailQueryWrapper.eq("order_id",orderid);
				List<XlCustomerOrderDetail> orderDetails = xlCustomerOrderDetailMapper.selectList(detailQueryWrapper);
				if(ObjectUtil.isEmpty(orderDetails)){
					msg.append(StrUtil.format("订单：{} 旺店通失败，原因是：订单数据异常",orderid));
					continue;
				}
				//构造旺店通接口参数，订单列表节点 trade_list
				//https://open.wangdian.cn/Y/open/apidoc/doc?path=trade_push_Y
				PlatformOrderCreateParam param = new PlatformOrderCreateParam();
				//构造旺店通订单货品明细节点order_list
				List<PlatformOrderItemCreateParam> order_list = new ArrayList<>();
				int i = 0 ;
				for(XlCustomerOrderDetail orderDetail : orderDetails){
					//根据 upc_code 查询wdt 商品信息
					WdtGoodsSpecList wdtGoodsSpecList = wdtGoodsSpecListMapper.getOneSpecByGoodNo(orderDetail.getUpcCode());
					if(ObjectUtil.isEmpty(wdtGoodsSpecList)){
						msg.append(StrUtil.format("商品：{} 未在旺店通建档，无法推送",orderDetail.getUpcCode()));
						return  Result.ok(msg.toString());
					}
					PlatformOrderItemCreateParam orderCreateDetail = new PlatformOrderItemCreateParam();
					orderCreateDetail.setOid(orderInfo.getOrderCode()+"-"+i);//子订单编号
					orderCreateDetail.setNum(String.valueOf(orderDetail.getOrderQuantity()));//数量
					orderCreateDetail.setPrice(String.valueOf(orderDetail.getProductPrice().doubleValue()));//单价
					orderCreateDetail.setStatus("30");//状态
					orderCreateDetail.setRefundStatus("0");//退款状态,0:无退款,1:取消退款,2:已申请退款,3:等待退货,4:等待收货,5:退款成功

					orderCreateDetail.setGoodsId(String.valueOf(wdtGoodsSpecList.getGoodsId()));//平台货品ID 平台系统货品（SPU）的唯一标识。goods_id不能为空
					orderCreateDetail.setGoodsNo(wdtGoodsSpecList.getGoodsNo());//	平台货品SPU编码，对应ERP货品编号，尽量不为空

					orderCreateDetail.setSpecId(wdtGoodsSpecList.getSpecId());//	平台规格ID  平台系统单品（SKU）的的唯一标识，尽量不为空，spec_id和spec_no区别与SPU、SKU概念介绍，单击这里
					orderCreateDetail.setSpecNo(wdtGoodsSpecList.getSpecNo());//规格编码	spec_no 	平台货品SKU唯一码，对应ERP商家编码，goods_no和spec_no不能同时为空

					orderCreateDetail.setGoodsName(wdtGoodsSpecList.getGoodsName());	//	平台货品名称
					orderCreateDetail.setAdjustAmount("0");//	客服调整总金额(大于0加价，小于0减价，是折扣来源的一部分,没有传0)
					orderCreateDetail.setDiscount("0");//优惠	 	下单总折扣，客户下单时折扣(比如促销打折，不包含客服调整、分摊折扣，没有传0)
					orderCreateDetail.setShareDiscount("0");	// 	 是	分摊总折扣，由总订单分摊而来，一般是付款时产生，如使用优惠券，没有传0。
					i++;
					order_list.add(orderCreateDetail);
				}
				param.setTid(orderInfo.getOrderCode());////平台订单号(相同tid只能推送一次),指商城、官网等平台的订单编号,原始单号
				param.setTradeStatus(30);//平台订单状态：10待支付 30已支付40 部分发货 50已发货 70已完成 80已退款 90已关闭(付款前取消)
				param.setDeliveryTerm("1");//发货条件,1:款到发货,2:货到付款(包含部分货到付款),3:分期付款,4:挂账
				param.setTradeTime(DateUtil.formatDateTime(orderInfo.getCreateTime()));//  下单时间,平台订单创建时间,时间格式：yyyy-MM-dd HH:mm:ss
				param.setPayTime(DateUtil.formatDateTime(orderInfo.getPaymentTime()));//支付时间	,平台订单付款时间,时间格式：yyyy-MM-dd HH:mm:ss，未付款订单为:null
				param.setBuyerNick(orderInfo.getStoreName());//平台买家昵称，注意：一次推送网名相同的订单不能超过30
				param.setReceiverName(orderInfo.getReceiptName());//收件人姓名
				param.setReceiverProvince(orderInfo.getProvince());
				param.setReceiverCity(orderInfo.getCity());
				param.setReceiverDistrict(orderInfo.getDistrict());
				param.setReceiverMobile(orderInfo.getReceiptPhone());
				param.setReceiverAddress(orderInfo.getReceiptAddress());
				param.setBuyerMessage(orderInfo.getOrderNotes());//买家备注
				param.setPostAmount("0");//	商家收取买家的物流或者快递费用
				param.setCodAmount("0");//	货到付款金额    cod金额=(price * num + adjust_amount -discount – share_discount）+post_amount+ext_cod_fee-paid
				param.setExtCodFee("0");//货到付款买家费用，扣除货到付款订单金额后，卖家仍需支付的货到付款其他金额。这个钱卖家收不回来，是快递公司直接收走，但在快递单里是要打印出来，否则快递收款就错了
				param.setOtherAmount("0");	// 其它应从买家收取的服务费，其他费用
				if(ObjectUtil.isEmpty(orderInfo.getPaymentAmount())){
					param.setPaid(String.valueOf(orderInfo.getTotalAmount()));
				}else {
					param.setPaid(String.valueOf(orderInfo.getPaymentAmount()));
				}//已付
				//param.setItemCreateParamList(order_list);
				param.setOrderList(order_list);
				trade_list.add(param);

				//一个订单一个订单的推送给 WDT
				WdtClient client = new WdtClient(CommonConstants.sid, CommonConstants.appkey, CommonConstants.appSecret, CommonConstants.baseUrlProd);
				Map<String, String> params = new HashMap<String, String>();
				params.put("trade_list", JSONUtil.toJsonStr(trade_list));
				params.put("shop_id","2");
				System.out.println(params);
				String response = client.execute("trade_push.php", params);
				System.out.println(response);
				JSON resultJson = JSONUtil.parseObj(response);
				int code = Integer.parseInt(resultJson.getByPath("code").toString());
				String message = resultJson.getByPath("message").toString();
				int new_count = Integer.parseInt(resultJson.getByPath("new_count").toString());
				int chg_count = Integer.parseInt(resultJson.getByPath("chg_count").toString());
				if(code != 0){
					xlLogUtil.insertLog(orderInfo.getOrderCode(),"回传旺店通","回传旺店通失败,原因是："+msg,new Date(),orderInfo.getOrderStatus(),orderInfo.getOrderStatus());
					return  Result.ok("回传旺店通失败,原因是：" + msg);
				}else{
					if(new_count > 0||chg_count>0){//有新增
						Map<String, String> paramsQuery = new HashMap<String, String>();
						paramsQuery.put("src_tid", orderInfo.getOrderCode());
						String responseQuery = client.execute("trade_query.php", paramsQuery);
						JSON responseQueryJson = JSONUtil.parseObj(responseQuery);
						JSONArray array_temp =  JSONUtil.parseArray(responseQueryJson.getByPath("trades"));
						if(ObjectUtil.isEmpty(array_temp)){
							//xlLogUtil.insertLog(orderInfo.getOrderCode(),"回传旺店通","回传旺店通失败,没有查到单号，原因是未知，请核查",new Date(),orderInfo.getOrderStatus(),orderInfo.getOrderStatus());
							return  Result.ok("回传旺店通失败,没有查到单号，原因是未知，请核查");
						}
						String wdtOrderId = "";
						JSON listJson = JSONUtil.parseObj(array_temp.get(0));
						wdtOrderId = listJson.getByPath("trade_no").toString();
						orderInfo.setKmSid(wdtOrderId);
						xlCustomerOrdeMapper.updateById(orderInfo);
						//更新明细的km_sid
						for(XlCustomerOrderDetail orderDetailTemp : orderDetails){
							orderDetailTemp.setKmSid(wdtOrderId);
							xlCustomerOrderDetailMapper.updateById(orderDetailTemp);
						}
						//
						xlLogUtil.insertLog(orderInfo.getOrderCode(),"回传旺店通","回传旺店通成功,旺店通系统单号是："+wdtOrderId,new Date(),orderInfo.getOrderStatus(),orderInfo.getOrderStatus());
						return  Result.ok("回传旺店通成功,旺店通系统单号是：" + wdtOrderId);

					}else{//只更新了订单
						xlLogUtil.insertLog(orderInfo.getOrderCode(),"回传旺店通","回传旺店通成功,更新订单：",new Date(),orderInfo.getOrderStatus(),orderInfo.getOrderStatus());
						return  Result.ok("回传旺店通成功,更新了订单" );
					}
				}
			}

		}catch (Exception e){
			e.printStackTrace();
			return Result.error("回传旺店通失败,原因未知。");
		}
		return Result.error("回传旺店通失败,原因未知。");
	}

	@Override
	public IPage<XlCustomerOrde> pageNew(Page<XlCustomerOrde> page, QueryWrapper<XlCustomerOrde> queryWrapper) {
		return xlCustomerOrdeMapper.orderQueryPageNew(page,queryWrapper);
	}

    @Override
    public List<Map> queryBrandOfOrderDetail(String brand, int month) {
        return xlCustomerOrdeMapper.queryBrandOfOrderDetail(brand,month);
    }


    private IXlKuaidi100LogitraceService logitraceService;
    public XlCustomerOrdeServiceImpl (@Lazy IXlKuaidi100LogitraceService circB) {
        this.logitraceService = circB;
    }
    @Override
    public String handleRefreshLogistics(String orderCode, String logiCode) {
        //自动更新订单为状态为 已签收
        UpdateWrapper<XlCustomerOrde> ordeUpdateWrapper = new UpdateWrapper<>();
        ordeUpdateWrapper.set("order_status", "待收货")
                .eq("order_code", orderCode)
                .eq("order_status", "已收货");
        this.update(ordeUpdateWrapper);
        String l = logiCode.split(":")[1];
        //删除物流轨迹明细
       logitraceService.remove(new QueryWrapper<XlKuaidi100Logitrace>().eq("logi_code", l));
        return "更新成功";
    }


}
